import cv2
import time
import os
import numpy as np

class Camera:
    def __init__(self, source=0):
        # source = "http://192.168.123.12:8080/?action=stream"
        self.cap = cv2.VideoCapture(source)

    def getframe(self):
        ret, frame = self.cap.read()
        return frame

    def getframe_rgb(self):
        ret, frame = self.cap.read()
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    def showframe(self, frame, window_name='result'):
        cv2.imshow(window_name, frame)

    def close(self):
        self.cap.release()

    def writeframe(self, frame, filename=''):
        if filename=='':
            filename = './result' + time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) + '.jpg'
        cv2.imwrite(filename, frame)



path_imgs = './imgs'
# path_imgs = r'E:\Datasets\WisdomGuide\val'

class Camera_virtual():
    index = 0
    def __init__(self, path_imgs=path_imgs, imgs_num=-1):
        files = os.listdir(path_imgs)[0:imgs_num]
        self.frames = []
        for file in files:
            if not os.path.isdir(file):
                frame = cv2.imread(path_imgs + os.path.sep + file)
                self.frames.append(frame)
        return

    def getframe(self):
        return self.frames[self.index]

    def getframe_rgb(self):
        frame = self.frames[self.index]
        return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    
    def nextframe(self):
        while True:
            yield self.frames[self.index]
            index += 1
            if self.index>=len(self.frames): index = 0

    def get_frame_byte(self):
        frame = self.frames[self.index]
        return cv2.imencode('.jpg', frame)[1].tobytes()



class Camera_rs:
    def __init__(self) -> None:
        import pyrealsense2 as rs

        # Configure depth and color streams
        self.pipeline = rs.pipeline()
        config = rs.config()
        # Get device product line for setting a supporting resolution
        pipeline_wrapper = rs.pipeline_wrapper(self.pipeline)
        pipeline_profile = config.resolve(pipeline_wrapper)
        device = pipeline_profile.get_device()
        device_product_line = str(device.get_info(rs.camera_info.product_line))

        found_rgb = False
        for s in device.sensors:
            if s.get_info(rs.camera_info.name) == 'RGB Camera':
                found_rgb = True
                break
        if not found_rgb:
            print("The demo requires Depth camera with Color sensor")
            exit(0)

        if device_product_line == 'L500':
            config.enable_stream(rs.stream.color, 960, 540, rs.format.bgr8, 30)
        else:
            config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

        # Start streaming
        self.pipeline.start(config)


    def getframe(self):
        frames = self.pipeline.wait_for_frames()
        color_frame = frames.get_color_frame()
        if not color_frame:
            print('Can not get color frame.')
            return False
    
        # Convert images to numpy arrays
        frame = np.asanyarray(color_frame.get_data()) # color_image
        return frame


    def close(self):
        pass
    